﻿using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Domain.PM;
using FarmSmartSleep.Common.Domain.PM.select;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;

namespace FarmSmartSleep.Organ.API.Application.ProductionManagement.SheepTransferCommands
{
    public class SheepTransferSearchHander : IRequestHandler<SheepTransferSearchCommand, ResultPage<SheepTransListDto>>
    {

        private readonly IBaseRepository<SheepTransfer> sheepTransRespository;
        private readonly IBaseRepository<SheepTransferType> sheepTransTypeRespository;
        private readonly IBaseRepository<SleepInfor> sleepInforRepository;
        private readonly IBaseRepository<Cottages> cottageRepository;
        private readonly IBaseRepository<Fields> fieldsRepository;
        private readonly IBaseRepository<Variety> VarietyRepository;
        private readonly IBaseRepository<Employee>employeeRepository;
        private readonly ILogger<SheepTransferSearchHander> logger;

        public SheepTransferSearchHander(IBaseRepository<SheepTransfer> sheepTransRespository, IBaseRepository<SheepTransferType> sheepTransTypeRespository, IBaseRepository<SleepInfor> sleepInforRepository, IBaseRepository<Cottages> cottageRepository, IBaseRepository<Fields> fieldsRepository, IBaseRepository<Variety> varietyRepository, IBaseRepository<Employee> employeeRepository, ILogger<SheepTransferSearchHander> logger)
        {
            this.sheepTransRespository = sheepTransRespository;
            this.sheepTransTypeRespository = sheepTransTypeRespository;
            this.sleepInforRepository = sleepInforRepository;
            this.cottageRepository = cottageRepository;
            this.fieldsRepository = fieldsRepository;
            VarietyRepository = varietyRepository;
            this.employeeRepository = employeeRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 分页查询转舍信息
        /// </summary>
        /// <param name="request">分页查询转舍信息请求对象</param>
        /// <param name="cancellationToken">允许异步</param>
        /// <returns>分页查询转舍信息响应对象</returns>
        public async Task<ResultPage<SheepTransListDto>> Handle(SheepTransferSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new ResultPage<SheepTransListDto>();

                var list = (from a in sheepTransRespository.GetAll().Where(c => !c.Deletes)
                            join b in sheepTransTypeRespository.GetAll() on a.SheepTransferTypeId equals b.SheepTransferTypeId
                            join c in sleepInforRepository.GetAll() on a.EarNo equals c.SleepInforId
                            join d in cottageRepository.GetAll() on a.OuBarn equals d.CottagesId
                            join e in fieldsRepository.GetAll() on a.OutPen equals e.FieIdId
                            join f in cottageRepository.GetAll() on a.TransferBarn equals f.CottagesId
                            join g in fieldsRepository.GetAll() on a.TransferPen equals g.FieIdId
                            join h in VarietyRepository.GetAll() on c.VarietyId equals h.VarietyId
                            join i in employeeRepository.GetAll() on a.CreateId equals i.EmployeeId
                            select new SheepTransListDto
                            {
                                SheepTransferId = a.SheepTransferId,
                                TransferDate = a.TransferDate,
                                DocumentNo = a.DocumentNo,
                                SerialNo = a.SerialNo,
                                EarNo = a.EarNo,
                                EarNumbewr = c.EarNumber,
                                TransferBarn = a.TransferBarn,
                                TransferPen = a.TransferPen,
                                OuBarn = a.OuBarn,
                                OutPen = a.OutPen,
                                Notes = a.Notes,
                                SheepTransferTypeId = a.SheepTransferTypeId,
                                SheepTransferTypeName = b.SheepTransferTypeName,
                                CreateId = a.CreateId,
                                CreateTime = a.CreateTime,
                                CreateName = i.FirstName,
                                ToCottageName = f.CottageName,
                                ToFieldName = g.FieIdName,
                                CottageName = d.CottageName,
                                FieldName = e.FieIdName,
                                VarietyId = c.VarietyId,
                                VarietyName = h.VarietyName,
                                Gender = c.Gender,
                                UpdateId = a.UpdateId,
                                ExamId = a.ExamId,
                                UpdateTime = a.UpdateTime,
                                ExamTime = a.ExamTime,
                                

                            }).ToList();
                foreach (var item in list)
                {
                    if (item.UpdateId > 0)
                    {
                        item.UpdateName = employeeRepository.GetAll().FirstOrDefault(c => c.EmployeeId == item.UpdateId).FirstName;
                    }
                    if (item.ExamId > 0)
                    {
                        item.ExamName = employeeRepository.GetAll().FirstOrDefault(c => c.EmployeeId == item.ExamId).FirstName;
                    }
                }
                if (!string.IsNullOrEmpty(request.StartDate))
                {
                    list = list.Where(c => c.TransferDate >= Convert.ToDateTime(request.StartDate)).ToList();
                }
                if (!string.IsNullOrEmpty(request.EndDate))
                {
                    list = list.Where(c => c.TransferDate <= Convert.ToDateTime(request.EndDate)).ToList();
                }
                if(request.SheepTransferTypeId!=0)
                {
                    list = list.Where(c => c.SheepTransferTypeId == request.SheepTransferTypeId).ToList();
                }
                if (request.TransferBarn != 0)
                {
                    list = list.Where(c => c.TransferBarn == request.TransferBarn).ToList();
                }
                if (request.TransferPen != 0)
                {
                    list = list.Where(c => c.TransferPen == request.TransferPen).ToList();
                }
                if (request.OutPen != 0)
                {
                    list = list.Where(c => c.OutPen == request.OutPen).ToList();
                }
                if (request.OuBarn != 0)
                {
                    list = list.Where(c => c.OuBarn == request.OuBarn).ToList();
                }
                if(!string.IsNullOrEmpty(request.EarNumbewr))
                {
                    list = list.Where(c => c.EarNumbewr.Contains(request.EarNumbewr)).ToList();
                }

                if (request.PageIndex != 0)
                {
                    result.totalCount = list.Count();
                    result.totalPage = (int)Math.Ceiling((result.totalCount) * 1.0 / request.PageSize);
                    result.Data = list.OrderBy(c => c.SheepTransferId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                }
                else
                {
                    result.Data =  list;
                }
                return result;



            }
            catch (Exception ex )
            {
                logger.LogError("获取分页显示转舍信息方法调用出错" + ex);
                throw;
            }
        }
    }
}
